package Servlets.qy;

import Bean.*;
import Util.GokJDBCUtil2;
import Util.RES;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "StockInServlet", urlPatterns = {"/StockInServlet", "/pages/stock_manage/StockInServlet"})
public class StockInServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        try {
            switch (action) {
                case "getOrders":
                    getOrders(request, out);
                    break;
                case "getOrderDetails":
                    getOrderDetails(request, out);
                    break;
                case "completeInbound":
                    completeInbound(request, out);
                    break;
                case "cancelInbound":
                    cancelInbound(request, out);
                    break;
                case "deleteInbound":
                    deleteInbound(request, out);
                    break;
                case "getproductname":
                    getproductByproid(request, out);
                    break;
                default:
                    out.print(RES.fail("无效的操作"));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("服务器内部错误: " + e.getMessage()));
        }
    }

    private void getproductByproid(HttpServletRequest request, PrintWriter out) {
        try {
            int proid = Integer.parseInt(request.getParameter("proid"));
            String sql = "SELECT * FROM product WHERE isdeleted = 0 and proid = ?";
            Product products = GokJDBCUtil2.queryForObject(sql, Product.class, proid);
            out.print(RES.success(products));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("获取商品名称失败"));
        }
    }

    // 获取入库订单列表（带分页功能）
    private void getOrders(HttpServletRequest request, PrintWriter out) {
        try {
            String status = request.getParameter("status"); // "pending" or "completed"
            String code = request.getParameter("code");
            String currentPageStr = request.getParameter("currentPage");
            String pageSizeStr = request.getParameter("pageSize");

            int currentPage = 1;
            int pageSize = 10;

            if (currentPageStr != null && !currentPageStr.isEmpty()) {
                currentPage = Integer.parseInt(currentPageStr);
            }

            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }

            String orderStatus = "0"; // 默认待入库

            if ("completed".equals(status)) {
                orderStatus = "1"; // 已入库
            }

            // 构建查询总数的SQL
            String countSql = "SELECT COUNT(*) FROM purchase_order po " +
                    "LEFT JOIN supplier s ON po.supplierid = s.id " +
                    "WHERE po.orderstatus = ? AND po.isdeleted = 0 ";

            // 处理订单编号参数
            if (code != null && !code.trim().isEmpty()) {
                countSql += "AND po.code LIKE '%" + code + "%' ";
            }

            // 获取总记录数
            int totalCount = GokJDBCUtil2.queryForCount(countSql, orderStatus);
            int totalPage = (int) Math.ceil((double) totalCount / pageSize);

            // 计算偏移量
            int offset = (currentPage - 1) * pageSize;

            String sql = "SELECT po.id, po.code, po.ordertime as orderTime, po.totalamount as totalAmount, " +
                    "po.orderstatus as orderStatus, s.name as supplierName " +
                    "FROM purchase_order po " +
                    "LEFT JOIN supplier s ON po.supplierid = s.id " +
                    "WHERE po.orderstatus = ? AND po.isdeleted = 0 ";

            // 处理订单编号参数
            if (code != null && !code.trim().isEmpty()) {
                sql += "AND po.code LIKE '%" + code + "%' ";
            }

            // 添加排序和分页
            sql += "ORDER BY po.ordertime DESC LIMIT " + offset + ", " + pageSize;

            List<StockPurchase> orders = GokJDBCUtil2.queryAll(sql, StockPurchase.class, orderStatus);

            // 构造返回结果
            StockMessage<StockPurchase> msg = new StockMessage<>(orders,String.valueOf(totalCount), String.valueOf(totalPage),String.valueOf(currentPage), String.valueOf(pageSize));
            out.print(RES.success(msg));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("获取入库订单失败"));
        }
    }

    // 获取订单详情
    private void getOrderDetails(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 查询订单详情，包含产品名称
            String sql = "SELECT pod.*, p.proname FROM purchase_order_detail pod " +
                    "LEFT JOIN product p ON pod.proid = p.id " +
                    "WHERE pod.orderid = ? AND pod.isdeleted = 0";

            List<StockPurchaseDetail> details = GokJDBCUtil2.queryAll(sql, StockPurchaseDetail.class, orderId);
            out.print(RES.success(details));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("获取订单详情失败"));
        }
    }

    // 完成入库
    private void completeInbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 1. 更新订单状态为已入库
            String updateOrderSql = "UPDATE purchase_order SET orderstatus = 1 WHERE id = ?";
            int orderResult = GokJDBCUtil2.update(updateOrderSql, orderId);

            if (orderResult <= 0) {
                out.print(RES.fail("订单不存在或已删除"));
                return;
            }

            // 2. 获取订单详情
            String detailSql = "SELECT * FROM purchase_order_detail WHERE orderid = ? AND isdeleted = 0";
            List<purchase_order_detail> details = GokJDBCUtil2.queryAll(detailSql, purchase_order_detail.class, orderId);

            // 3. 更新产品库存
            for (purchase_order_detail detail : details) {
                String updateProductSql = "UPDATE product SET quantity = quantity + ? WHERE id = ?";
                GokJDBCUtil2.update(updateProductSql, detail.getProquantity(), detail.getProid());
            }

            out.print(RES.success("入库成功"));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("入库失败: " + e.getMessage()));
        }
    }

    // 取消入库
    private void cancelInbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            String sql = "UPDATE purchase_order SET orderstatus = 2 WHERE id = ?"; // 2表示已取消
            int result = GokJDBCUtil2.update(sql, orderId);

            if (result > 0) {
                out.print(RES.success("订单已取消"));
            } else {
                out.print(RES.fail("订单不存在或已删除"));
            }
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("取消订单失败"));
        }
    }

    // 删除入库订单（逻辑删除）
    private void deleteInbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 逻辑删除订单和订单详情
            String updateOrderSql = "UPDATE purchase_order SET isdeleted = 1 WHERE id = ?";
            String updateDetailSql = "UPDATE purchase_order_detail SET isdeleted = 1 WHERE orderid = ?";

            GokJDBCUtil2.update(updateOrderSql, orderId);
            GokJDBCUtil2.update(updateDetailSql, orderId);

            out.print(RES.success("订单已删除"));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("删除订单失败"));
        }
    }
}
